package netclient;

import java.net.*;
import java.io.*;
import java.util.Scanner;

public class TestClient {
	final static String 	HOST = "localhost";
	final static int 		PORT = 8576;

	static Socket sock = null;
	static PrintWriter netOut;
	static Scanner netIn;

	static MessageHandler msgHand;
	
	public static void main(String[] args) {
		while (sock == null) {
			try {
				System.out.println("Attempting to connect to: " + HOST + ":" + PORT);
				sock = new Socket(HOST, PORT);
				netOut = new PrintWriter(sock.getOutputStream());
				netIn = new Scanner(sock.getInputStream());
			} catch (Exception e) {
				try {Thread.sleep(5000);} catch(Exception e2) {};
			}
		}

		System.out.println("preparing to construct msgHand");
		msgHand = new MessageHandler(sock, netIn, null);
		msgHand.start();

		System.out.println("Connected.");
		boolean flag = true;
		while (flag){
			System.out.println("Type a command to send to the server:");

			Scanner sc = new Scanner(System.in);
			String cmd = sc.nextLine();

			if (cmd.equals("exit")) {flag = false; shutdown(); System.exit(0);}
			
			sendMessage(cmd);
			
		}
	}

	public static boolean sendMessage( String s ) {
		boolean flag = false;
		while (!flag) {
			try {
				netOut.println(s);
				netOut.flush();
				flag = true;
			} catch (Exception e) {
				flag = false;
			}	
		}
		return true;
	}

	public static void shutdown() {
		try {
			sendMessage("bye");
			netIn.close();
			netOut.close();
			sock.close();
		} catch(Exception e) {e.printStackTrace();}

		sock = null;
	}

	public void finalize() {
		try {
			netIn.close();
			netOut.close();
			sock.close();
		} catch(Exception e) {e.printStackTrace();}

		sock = null;
	}
}